package com.p2l.letterblocks;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.app.Activity;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityCreateUser extends Activity {
	private LinearLayout background;
	private TextView lUsername, lEmail, lPassword, lConfirm;
	private EditText username, email, password, confirm;
	private ProgressBar progress;
	private Context context;
	private Button create;
	
	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.create_user);
		
		context = this;
		
		background = (LinearLayout) findViewById(R.id.create_background);
		lConfirm = (TextView) findViewById(R.id.lblStarConfirmPassword);
		lUsername = (TextView) findViewById(R.id.lblStarUsername);
		lPassword = (TextView) findViewById(R.id.lblStarPassword);
		lEmail = (TextView) findViewById(R.id.lblStarEmail);

		confirm = (EditText) findViewById(R.id.txtCreateConfirmPassword);
		username = (EditText) findViewById(R.id.txtCreateUsername);
		password = (EditText) findViewById(R.id.txtCreatePassword);
		progress = (ProgressBar) findViewById(R.id.pbrCreate);
		email = (EditText) findViewById(R.id.txtCreateEmail);
		
		create = (Button) findViewById(R.id.btnCreate);
		create.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				lUsername.setVisibility(View.INVISIBLE);
				lEmail.setVisibility(View.INVISIBLE);
				lPassword.setVisibility(View.INVISIBLE);
				lConfirm.setVisibility(View.INVISIBLE);
				
				boolean accepted = true;
				
				if (username.length() < 1 || username.length() > 20 || !username.getText().toString().matches("[a-zA-Z0-9]+")) {
					lUsername.setVisibility(View.VISIBLE);
					accepted = false;
				}
				if (email.length() < 1 || email.length() > 50 || !email.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+")) {
					lEmail.setVisibility(View.VISIBLE);
					accepted = false;
				}
				if (password.length() < 1 || password.length() > 20) {
					lPassword.setVisibility(View.VISIBLE);
					accepted = false;
				}
				if (confirm.length() < 1 || !confirm.getText().toString().equals(password.getText().toString())) {
					lConfirm.setVisibility(View.VISIBLE);
					accepted = false;
				}
				
				// if criteria accepted, create user
				if (accepted) {
					progress.setVisibility(View.VISIBLE);
					create.setVisibility(View.GONE);
					new UserTask().execute();
				}
			}
		});
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (background.getBackground() != null)
			background.getBackground().setCallback(null);
		if (create.getBackground() != null)
			create.getBackground().setCallback(null);
		if (username.getBackground() != null)
			username.getBackground().setCallback(null);
		if (email.getBackground() != null)
			email.getBackground().setCallback(null);
		if (password.getBackground() != null)
			password.getBackground().setCallback(null);
		if (confirm.getBackground() != null)
			confirm.getBackground().setCallback(null);
		
		background = null;
		lUsername = null;
		lPassword = null;
		lConfirm = null;
		username = null;
		password = null;
		progress = null;
		confirm = null;
		context = null;
		create = null;
		lEmail = null;
		email = null;
		
		System.gc();
	}
	
	private class UserTask extends AsyncTask<Void, Void, Boolean> {
		private InputStream in;
		private XmlPullParser parser;
		private ArrayList<User> users;
		
    	@Override
		protected Boolean doInBackground(Void... params) {
			try {
				in = Server.open(Server.URL_USERS + "?username=" + username.getText().toString() + "&email=" + email.getText().toString());
				parser = Server.toXmlParser(in);
				users = XmlParser.getUsers(parser);
				
				if (users.size() == 0) {
					String sql = Server.URL_CREATE_USER + "?username=" + username.getText().toString() + "&password=" + password.getText().toString() + "&email=" + email.getText().toString();
					in = Server.open(sql);
					parser = Server.toXmlParser(in);
					int id = XmlParser.login(parser);
					in.close();
					sql = null;
					
					if (id == -1) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(context, getResources().getString(R.string.error_creating_user), Toast.LENGTH_LONG).show();
							}
			    		});
						return false;
					}
				} else {
					boolean bUsername = false;
					boolean bEmail = false;
					int i = 0;
					
					while (!bUsername && !bEmail && i < users.size()) {
						if (users.get(i).getUsername().equals(username.getText().toString())) {
							bUsername = true;
						} else if (users.get(i).getEmail().equals(email.getText().toString())) {
							bEmail = true;
						} else {
							i++;
						}
					}
					
					if (bUsername) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(context, getResources().getString(R.string.error_username_taken), Toast.LENGTH_LONG).show();
							}
			    		});
					} else if (bEmail) {
						runOnUiThread(new Runnable() {
							@Override
							public void run() {
								Toast.makeText(context, getResources().getString(R.string.error_email_used), Toast.LENGTH_LONG).show();
							}
			    		});
					}
					return false;
				}
			} catch (IOException e) {
				Log.e("LetterBlocks", e.toString());
			} catch (XmlPullParserException e) {
				Log.e("LetterBlocks", e.toString());
			}
			
			return true;
		}
    
	    @Override
	    protected void onPostExecute(Boolean success) {
	    	if (success) {
	    		finish();
	    	} else {
	    		runOnUiThread(new Runnable() {
					@Override
					public void run() {
						create.setVisibility(View.VISIBLE);
						progress.setVisibility(View.GONE);
					}
	    		});
	    	}

			in = null;
			parser = null;
			users.clear();
			users = null;
	    	this.cancel(true);
	    }
	}
}
